package com.example.dma.controller;

import com.example.dma.pojo.request.LoginRequest;
import com.example.dma.pojo.request.RegisterRequest;
import com.example.dma.pojo.User;
import com.example.dma.service.UserService;
import com.example.dma.util.jwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mainapi")
@CrossOrigin(origins = "http://localhost:5173")
public class MainController {
    @Autowired
    private UserService userService;
    @Autowired
    private jwtUtil jwtUtil;

    @GetMapping("/getUserInfo")
    public ResponseEntity<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String authorizationHeader) {
        // 提取 Bearer Token
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("error", "Invalid token"));
        }
        String token = authorizationHeader.substring(7);

        // 验证 Token 并获取用户信息
        try {
            String username = jwtUtil.getUsernameFromToken(token);
            User user = userService.getUserByUsername(username);

            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of("error", "User not found"));
            }

            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("name", user.getUsername());
            responseData.put("email", user.getEmail());
            // 可添加更多字段

            return ResponseEntity.ok(responseData);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "Failed to retrieve user info"));
        }
    }

    //
}

